package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.Vo.PaymentItemVO;
import com.hospital.hospitalserver.entity.Vo.PaymentVO;
import com.hospital.hospitalserver.entity.query.PaymentQuery;
import com.hospital.hospitalserver.mapper.PaymentMapper;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 收费信息相关实现方法
 * */
@Service
@RequiredArgsConstructor
public class PaymentService {
    private final PaymentMapper paymentMapper;

    /**
     * 管理端查询收费分页信息总行数
     */
    private Integer getPaymentMapperDataCountsBySearch(PaymentQuery query){
        return paymentMapper.getPaymentMapperDataCountsBySearch(query);
    }

    /**
     * 管理端查询收费分页-计算分页
     */
    private Integer getPaymentPageTotalBySearch(PaymentQuery query){
        Integer paymentTotalCounts = getPaymentMapperDataCountsBySearch(query);
        Integer pageTotal = 1;//设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = paymentTotalCounts/query.getPageSize();
        if(paymentTotalCounts%query.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 管理端查询收费分页信息
     */
    private List<PaymentVO> getPaymentMapperDataBySearch(PaymentQuery query){
        Integer currentPage = query.getCurrentPage();
        Integer startIndex = (currentPage - 1)* query.getPageSize();
        query.setStartIndex(startIndex);

        return paymentMapper.getPaymentMapperDataBySearch(query);
    }

    /**
     * 管理端查询收费分页信息
     * 装载数据
     */
    public Response getPaymentPagerDataBySearch(PaymentQuery query){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getPaymentMapperDataCountsBySearch(query));
        pagerData.setData(getPaymentMapperDataBySearch(query));
        pagerData.setPageTotal(getPaymentPageTotalBySearch(query));
        return Response.success(pagerData);
    }

    /**
     * 根据收费ID获取收费详情（包含项目明细）
     */
    public Response getPaymentDetailById(Integer paymentId) {
        PaymentVO payment = paymentMapper.getPaymentMainByPaymentId(paymentId);
        if (payment != null) {
            // 查询收费项目明细
            List<PaymentItemVO> items = paymentMapper.getPaymentItemsByPaymentId(paymentId);
            payment.setItems(items);
        }
        return Response.success(payment);
    }
}
